import BaseComponent from '../components/Base/BaseComponent';
import React from 'react'
import {BrowserRouter} from 'react-router-dom'
import {renderRoutes} from 'react-router-config'
import {enquireScreen, unenquireScreen} from 'enquire-js';
import {connect} from 'react-redux'

import {genRouter} from './router';

class AppRouteMap extends BaseComponent {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.enquireHandler = enquireScreen(mobile => {
            this.onSetValueToStore(['root', 'app', 'isMobile'], !!mobile);
        });
    }

    componentWillUnmount() {
        unenquireScreen(this.enquireHandler);
    }

    render() {
        // 权限过滤
        let routes = genRouter();

        // 一般用户的权限过滤
        if (this.props.user.get('type') > 0) {
            let rights = JSON.parse(this.props.user.get('rights', '[]'));
            let homeIndex = routes.findIndex(r => r.path === '/');
            routes[homeIndex].routes = routes[homeIndex].routes.filter(f => !!~rights.findIndex(r => r === f.path) || ['/','*'].includes(f.path));
        }

        return (
            <BrowserRouter>
                {renderRoutes(routes)}
            </BrowserRouter>
        )
    }
}

export default connect(
    state => ({
        user: state.root.user,
    })
)(AppRouteMap);